<template>
  <a-modal
    centered
    width="600px"
    :open="visibleModal"
    :title="`${userId ? '编辑' : '添加'}账号`"
    :mask-closable="false"
    :body-style="{ 'padding-bottom': '0' }"
    :ok-button-props="{
      loading: loading
    }"
    @ok="handleOk"
    @cancel="closeModal"
  >
    <a-spin :spinning="loading" tip="数据加载中">
      <a-form ref="formRef" :model="formState" name="basic" layout="vertical" class="my-a-form" :rules="rules">
        <div class="on-line-two-item">
          <a-form-item label="用户名称" name="username">
            <a-input v-model:value="formState.username" v-trim :maxlength="20" placeholder="请输入用户名称" />
          </a-form-item>
          <a-form-item label="手机号" name="tel">
            <a-input v-model:value="formState.tel" v-trim :maxlength="11" placeholder="请输入手机号" />
          </a-form-item>
        </div>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" v-trim :maxlength="100" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item v-if="isAdmin" label="角色" name="roleIds">
          <a-select
            v-model:value="formState.roleIds"
            mode="multiple"
            style="width: 100%"
            placeholder="请选择角色"
            :options="roleList"
            show-arrow
          />
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="formState.description" v-trim :rows="3" :maxlength="200" show-count placeholder="请输入描述" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script setup lang="ts">
  import { message, Modal, SelectProps } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { regex } from 'g6-fn'
  import { computed, createVNode, ref, watch } from 'vue'
  import { useRequest } from 'vue-request'

  import WarnIcon from '@/components/icon/IconWarn/index.vue'
  import { roleApi, userApi } from '@/services/api'

  export interface Props {
    visibleModal: boolean
    isAdmin?: boolean
    userId?: string
  }
  interface FormState {
    username: string
    tel: string
    email: string
    roleIds: string[]
    description?: string
  }
  const props = withDefaults(defineProps<Props>(), {
    isAdmin: false,
    userId: ''
  })

  const emits = defineEmits<{
    (e: 'update:visibleModal', params: boolean): void
    (e: 'update:userId', params: string): void
    (e: 'ok'): void
  }>()

  watch(
    () => props.visibleModal,
    () => {
      if (props.visibleModal) {
        if (props.userId) {
          getUserDetail(props.userId)
        }
        if (props.isAdmin) {
          getRoleListData()
        }
      }
    }
  )

  const formState = ref<FormState>({
    username: '',
    tel: '',
    email: '',
    roleIds: [],
    description: ''
  })
  const formRef = ref()

  let validateRoleIds = async () => {
    // 学生不需要校验角色
    if (!props.isAdmin) return Promise.resolve()
    if (formState.value.roleIds.length === 0) {
      return Promise.reject('请选择角色')
    } else {
      return Promise.resolve()
    }
  }

  const rules: Record<string, Rule[]> = {
    username: [
      { required: true, message: '请输入用户名称' },
      {
        pattern: regex.numName,
        message: '仅支持中英文、数字'
      }
    ],
    tel: [
      { required: true, message: '请输入手机号' },
      {
        pattern: regex.phone,
        message: '请输入正确的手机号'
      }
    ],
    email: [
      { required: true, message: '请输入邮箱地址' },
      {
        pattern: regex.email,
        message: '请输入正确的邮箱地址'
      }
    ],
    roleIds: [{ required: true, message: '请选择角色', validator: validateRoleIds, trigger: 'change' }]
  }

  const resetForm = () => {
    formState.value = {
      username: '',
      tel: '',
      email: '',
      roleIds: [],
      description: ''
    }
    formRef.value.resetFields()
  }

  const getUserDetail = async (id: string) => {
    const getDetailApi = props.isAdmin ? userApi.studentDetail : userApi.studentDetail
    const res = await getDetailApi(id)()
    Object.assign(formState.value, res.data)
  }

  const handleOk = async () => {
    await formRef.value.validateFields()

    props.userId ? editUser() : addUser()
  }

  const { runAsync: runEditStudent, loading: isEditStudentLoading } = useRequest<ResponseData<void>>(userApi.studentEdit)
  const { runAsync: runAddStudent, loading: isAddStudentLoading } = useRequest<ResponseData<boolean>>(userApi.studentAdd)
  const { runAsync: runEditAdmin, loading: isEditAdminLoading } = useRequest<ResponseData<void>>(userApi.adminEdit)
  const { runAsync: runAddAdmin, loading: isAddAdminLoading } = useRequest<ResponseData<boolean>>(userApi.adminAdd)

  const loading = computed(() => {
    return isEditStudentLoading.value || isAddStudentLoading.value || isEditAdminLoading.value || isAddAdminLoading.value
  })

  const editUser = async () => {
    const editApi = props.isAdmin ? runEditAdmin : runEditStudent
    await editApi(
      {
        id: props.userId,
        ...formState.value
      },
      { isAddUid: true }
    )
    message.success(props.userId ? '编辑成功' : '添加成功')
    closeModal()
    emits('ok')
  }

  const addUser = async () => {
    const addApi = props.isAdmin ? runAddAdmin : runAddStudent
    const res = await addApi(
      {
        ...formState.value
      },
      { isAddUid: true, noJudgeCode: true }
    )
    //此code表示用户的邮箱已被注册
    if (res.code === 'AUTH-100063') {
      Modal.confirm({
        icon: createVNode(WarnIcon),
        content: res.message,
        okText: '确定',
        cancelText: '取消',
        centered: true,
        onOk: async () => {
          await addApi(
            {
              ...formState.value,
              gitlabFlag: true
            },
            { isAddUid: true }
          )
          message.success('添加成功')
          closeModal()
          emits('ok')
        }
        // onCancel: async () => {
        //   await addApi(
        //     {
        //       ...formState.value,
        //       gitlabFlag: false
        //     },
        //     { isAddUid: true }
        //   )
        //   message.success('添加成功')
        //   closeModal()
        //   emits('ok')
        // }
      })
      return
    }
    if (res.code !== 'SYSTEM-100000') {
      message.error(res.message)
      return
    }
    message.success('添加成功')
    closeModal()
    emits('ok')
  }

  /* TODO:获取角色列表 */
  const roleList = ref<SelectProps['options']>([])

  const getRoleListData = async () => {
    const { data } = await roleApi.allList()
    roleList.value = data.map((role: any) => ({ label: role.name, value: role.id }))
  }

  function closeModal() {
    emits('update:visibleModal', false)
    emits('update:userId', '')
    resetForm()
  }
</script>

<style lang="less" scoped>
  .my-a-form {
    .on-line-two-item {
      display: flex;
      gap: 0 24px;

      .ant-form-item {
        width: 50%;
      }
    }

    .ant-form-item {
      margin-bottom: 40px;
      // 调整表单项间距之后，需考虑到出现错误提示的字段的高度，为24px
      &.ant-form-item-with-help {
        margin-bottom: 16px;
      }
    }

    .ant-form-item:last-of-type {
      margin-bottom: 0;
    }
  }
</style>
